import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'
const state = {
  token: getToken(),
  userId: '',
  username: '',
  realName: '',
  password: '',
  sceneIdList: [19, 28],
  sceneList: [],
  authorities: [],
  menuList: [],
  routerArr: [],
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, id) => {
    state.userId = id
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_REAL_NAME: (state, realName) => {
    state.realName = realName
  },
  SET_SCENE_ID_LIST: (state, sceneIdList) => {
    state.sceneIdList = sceneIdList
  },
  SET_SCENE_LIST: (state, sceneList) => {
    state.sceneList = sceneList
  },
  // 设置场景信息
  SET_SCENE_INFO: (state, val) => {
    state.sceneInfo = val
  },
  SET_AUTHORITIES: (state, authorities) => {
    state.authorities = authorities
  },
  SET_MENU_LIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_ROUTER_ARR: (state, routerArr) => {
    state.routerArr = routerArr
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // login({ username: username.trim(), password: md5(password), type: 'PWD' })
      login({ username: username.trim(), password: password, type: 'PWD' })
        .then(response => {
          if (response.data.code === 200) {
            const {
              data: { data }
            } = response
            // commit('SET_TOKEN', data['X-Access-Token'])
            // setToken(data['X-Access-Token'])
            commit('SET_TOKEN', 'ceshi')
            setToken('ceshi')
          } else {
            Message.error(response.data.message)
            reject(response.data.message)
          }
          commit('SET_MENU_LIST', [])
          commit('SET_ROUTER_ARR', [])
          sessionStorage.removeItem('menuList')
          resolve(true)
        })
        .catch(error => {
          Message.error(error.toString())
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo({ token: state.token, menuName: "显示端" })
        .then((response) => {
          const {
            userId,
            username,
            sceneIdList,
            menuList,
            authorities
          } = response.data.data.sysUser
          const sceneList = response.data.data.resSceneList
          // 接口中获取的 按钮权限
          sessionStorage.setItem(
            "authorities",
            JSON.stringify(authorities || "[]")
          );
          const data = {
            userId,
            roles: ["admin"],
            name: username,
            avatar: username,
            introduction: username,
            menuList
          };
          console.log(11111111, sceneList)
          commit('SET_USERNAME', username)
          commit('SET_SCENE_ID_LIST', sceneIdList)
          commit('SET_SCENE_LIST', sceneList)
          commit('SET_AUTHORITIES', authorities)
          commit('SET_MENU_LIST', menuList)
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '')
          // commit('SET_ROLES', [])
          removeToken()
          resetRouter()

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
